package com.zyd.service.meal.impl;

import com.google.common.collect.Maps;
import com.zyd.context.HeaderContext;
import com.zyd.io.model.MealEntity;
import com.zyd.io.model.MealEntityExample;
import com.zyd.io.model.RolePowerEntity;
import com.zyd.io.model.SafeEntity;
import com.zyd.io.page.OperateKey;
import com.zyd.io.page.PageBean;
import com.zyd.io.page.PageRequestBean;
import com.zyd.io.page.SearchKey;
import com.zyd.io.vo.page.MultiQueryPageVO;
import com.zyd.mappers.MealEntityMapper;
import com.zyd.service.meal.MealService;
import com.zyd.service.power.PowerService;
import com.zyd.service.setmeal.SetMealService;
import com.zyd.util.SqlUtils;
import com.zyd.util.ToolUtils;
import com.zyd.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

@Component
public class MealServiceImpl implements MealService {

    @Autowired
    private MealEntityMapper mapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SetMealService setMealService;

    @Autowired
        private PowerService powerService;

    @Override
    public List<MealEntity> findMealsByVeId(String id) {
        MealEntityExample example = new MealEntityExample();
        example.or().andVehicle_idEqualTo(id);
        example.setOrderByClause("create_time DESC");

        return mapper.selectByExample(example);
    }

    public MealEntity findLastMealByVeId(String id) {
        List<MealEntity> entities;
        return (entities = findMealsByVeId(id)).isEmpty() ? null : entities.get(0);

    }

    @Override
    public void updateMeal(MealEntity entity) {
        mapper.updateByPrimaryKey(entity);
    }

    @Override
    public void addMeal(MealEntity entity) {
        entity.setId(UUIDUtil.getUUid());
        SafeEntity meal = setMealService.findMeal(entity.getMeal_id());
        entity.setMeal_name(meal.getSalename());
        entity.setMeal_money(meal.getSalemny());
        entity.setHas_theftdutp(meal.getHas_theft());
        entity.setHas_thirdduty(meal.getHas_third());
        entity.setHas_accient(meal.getHas_accient());
        entity.setCreate_time(ToolUtils.getNowTime());

        mapper.insertSelective(entity);
    }
    @Override
    public PageBean<Map<String, Object>> findMealPage(MultiQueryPageVO request) {

        String str = "SELECT a.meal_name,a.start_time,a.end_time,a.vehicle_id, b.carname,b.mobile,b.tagcode,b.vinno,b.theftnum from zydzn_meal a LEFT JOIN zydzn_vehicle b ON a.vehicle_id = b.id WHERE 1 = 1 and  b.dr=0 ";

//            str +=SqlUtils.addMultiCondition(request.getSearchKeys());
        List<SearchKey> searchKeys = request.getSearchKeys();
        for (SearchKey searchKey : searchKeys) {
            if (searchKey.getName().equals("start_time")){
                str += " AND  start_time >=" +"'" +searchKey.getValue()+"'";
            }else if ( searchKey.getName().equals("end_time")){
                str += " AND  start_time <=" +"'" +searchKey.getValue()+"'";
            }else {
                str +=" AND "+searchKey.getName()+" "+searchKey.getOperate()+" '%"+searchKey.getValue()+"%'";
//                str +=SqlUtils.addMultiCondition(request.getSearchKeys());
            }
        }
        RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId((String) HeaderContext.get().get("userid"), "2010");
        if (rolePowerEntity != null && ! org.springframework.util.StringUtils.isEmpty(rolePowerEntity.getArea())) {

            str += " AND b.newareaid IN (" + SqlUtils.addIn(rolePowerEntity.getArea()) + ")";
        }
        else{
            return null;
        }
        String countSql = "select count(1) from (" + str + ") as a";
        Long totalRows = jdbcTemplate.queryForObject(countSql, Long.class);
        String pageSql = SqlUtils.addPage(str, request.getCurrentPage(), request.getPageSize());

        List<Map<String, Object>> ret = jdbcTemplate.query(pageSql, new RowMapper<Map<String, Object>>() {
            @Override
            public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
                Map<String, Object> ret = Maps.newHashMap();
                ret.put("vehicle_id", rs.getString("vehicle_id"));
                ret.put("carname", rs.getString("carname"));
                ret.put("mobile", rs.getString("mobile"));
                ret.put("tagcode", rs.getString("tagcode"));
                ret.put("theftnum", rs.getString("theftnum"));
                ret.put("meal_name", rs.getString("meal_name"));
                ret.put("start_time", rs.getString("start_time"));
                ret.put("end_time", rs.getString("end_time"));
                return ret;
            }
        });

        PageBean<Map<String, Object>> pageBean = new PageBean<Map<String, Object>>(request.getCurrentPage(),
                request.getPageSize(), totalRows.intValue());
        pageBean.setItems(ret);
        return pageBean;
    }
}
